// stores/counter.js
import {
  defineStore
} from 'pinia';
import storage from "../../path/storage"
import service from "@/path/service"
import {
  router
} from "@/path/router";
const defUserInfo = {
  avatar: "",
  createtime: null,
  expires_in: null,
  expiretime: null,
  id: null,
  mobile: "",
  nickname: "",
  token: "",
  user_id: null,
  username: "",
}
export const useUserInfoStore = defineStore('userInfo', {
  state: () => ({
    userInfo: storage.getLocalStorage("userinfoStorage") || defUserInfo,
    configs: {
      sys_phone: ""
    },
  }),
  actions: {
    setUserInfo(user) {
      storage.setLocalStorage("userinfoStorage", user)
      this.userInfo = user;
      this.getConfigs()
    },
    /**@param {*} params {
        jscode: res.code,
        phonecode: detail.code,
        nickname: "",
        avatar: ""
      }
     */
    loginUserInfo(params) {
      return service.post("api/user/wechatlogin", params).then((res) => {
        return this.getUserInfo(res.userinfo)
      })
    },
    getConfigs() {
      service.get("api/ycg/home/getconfigs").then((res) => {
        this.configs = res
      })
    },
    getUserInfo(user) {
      const _user = user || this.userInfo || {}
      if (!_user?.token) return Promise.reject()
      return service.post("api/ycg/usercenter/userinfo", {}, { token: _user?.token }).then((res) => {
        this.setUserInfo({
          ..._user,
          ...res,
        })
      }).catch(() => {
        this.setUserInfo(defUserInfo)
        uni.showModal({
          title: "温馨提示",
          showCancel: false,
          content: "用户信息获取失败，请重新登录",
          success() {
            router.reLaunch({
              url: "/pages/tabbar/index/index"
            })
          }
        })
      })
    }
  },
});